import { loginAPI } from '@/api/login'
import { getUserInfoAPI } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  getUserId,
  setUserId,
  removeUserId
} from '@/utils/auth'
// import { resetRouter } from '@/router'

// 初始化信息
const getDefaultState = () => {
  return {
    token: getToken() || null,
    userId: getUserId() || null,
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ID: (state, id) => {
    state.userId = id
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // 登录
  async login({ commit }, userInfo) {
    try {
      const { token, userId } = await loginAPI(userInfo)
      commit('SET_TOKEN', token)
      setToken(token)
      commit('SET_ID', userId)
      setUserId(userId)
    } catch (e) {
      console.log(e)
    }
  },

  // 获取用户信息
  async getInfo({ commit, state }) {
    try {
      const res = await getUserInfoAPI(state.userId)
      commit('SET_USER_INFO', res[0])
    } catch (e) {
      console.log(e)
    }
  },

  // 退出登录
  logout({ commit }) {
    try {
      removeToken()
      removeUserId()
      // resetRouter()
      commit('RESET_STATE')
    } catch (e) {
      console.log(e)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
